package cn.gson.springmvc.model.services;

import cn.gson.springmvc.model.Vo.DrugsZx;
import cn.gson.springmvc.model.Vo.PurchaseInfoZx;
import cn.gson.springmvc.model.dao.GonyingsDaoZx;
import cn.gson.springmvc.model.dao.PurchasingDaoZx;
import cn.gson.springmvc.model.dao.XiangqingDaoZx;
import cn.gson.springmvc.model.dao.YaoPinDaoZx;
import cn.gson.springmvc.model.pojos.GonyingsEntity;
import cn.gson.springmvc.model.pojos.PurchasingEntity;
import cn.gson.springmvc.model.pojos.XiangqingEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class PurchasingServicesZx {

    @Autowired
    YaoPinDaoZx yaoPinDaoZx;

    @Autowired
    XiangqingDaoZx xiangqingDaoZx;

    @Autowired
    PurchasingDaoZx purchasingDaoZx;

    @Autowired
    GonyingsDaoZx gonyingsDaoZx;

    @Transactional(value="transactionManager",rollbackFor = Exception.class)
    public void savePurchase(PurchaseInfoZx purchaseInfoZx){
        //生成采购单
        PurchasingEntity purc=new PurchasingEntity();
        purc.setZongjine(BigDecimal.valueOf(purchaseInfoZx.getAmount()));
        purc.setPurchasingShenpir(purchaseInfoZx.getUser());
        purc.setPurchasingData(new Timestamp(purchaseInfoZx.getValues().getTime()));
        purc.setPurchaseingZuantai(1);

        //供应商
        GonyingsEntity gys=gonyingsDaoZx.findById(new Long(purchaseInfoZx.getRegion())).get();
        purc.setGonyingsByPurchasingId(gys);

        purchasingDaoZx.save(purc);

        System.err.println(purc.getPurchasingId());
        //详情单
        List<DrugsZx> drugs= purchaseInfoZx.getDrugs();
        for (DrugsZx drug:drugs){
            XiangqingEntity xq=new XiangqingEntity();
            xq.setXiangqingSum(drug.getBuyNumber());//采购数量
            xq.setYaopinByYaopinId(yaoPinDaoZx.findById(new Long(drug.getYaopinId())).get());//药品id
            xq.setPurchasingByPurchasingId(purc);//采购id
            xiangqingDaoZx.save(xq);
        }

    }

}
